<?php

namespace App\Http\Controllers\Admin;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use App\Http\Controllers\Controller;
use Darabonba\OpenApi\Models\Config;
use Illuminate\Http\Request;

class SmsClient extends Controller
{
    /**
     * 使用AK&SK初始化账号Client
     * @return Dysmsapi Client
     */
   public static function createClient()
   {
       // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
       // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html。
       $config = new Config([
           // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
           "accessKeyId" => env("OSS_ID"),
           // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
           "accessKeySecret" => env("OSS_KEY")
       ]);
       // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
       $config->endpoint = "dysmsapi.aliyuncs.com";
       return new Dysmsapi($config);
   }

   public function sendSmsCode($mobile,$code)
   {
       $code = json_encode(['code'=>$code]);
       $client = self::createClient();
       $sendSmsRequest = new SendSmsRequest([
           "signName" => "博客空间",
           "templateCode" => "SMS_474205131",
           "phoneNumbers" => $mobile,
           "templateParam" => $code
       ]);
       $runtime = new RuntimeOptions([]);
       try{
          $result = $client->sendSmsWithOptions($sendSmsRequest,$runtime);
          if($result->statusCode==200) {
              if($result->body->code=='OK'){
                  return ['status'=>'200','msg'=>'短信发送成功'];
              }else{
                  return ['status'=>'201','msg'=>'短信发送失败'];
              }
          }else{
              return ['status'=>'201','msg'=>'短信发送失败'];
          }
       }catch (\Exception $exception){

       }
   }

}
